﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using System.Collections;

namespace LCWMS
{
    public partial class  w_so063 : DockContent
    {
        DataSet dscustomer;
        DataSet ds_tran;
        Cursor currentCursor = Cursor.Current;

        public w_so063()
        {
            InitializeComponent();
            dgv_tran.AutoGenerateColumns = false;
        }



        //添加采购定单的合计行
        private void f_add_order()
        {
            decimal d_1, d_2, d_3, d_4, d_5, d_6, d_7;
            DataTable dt_put;
            //增加一个合计行 
            dt_put = (DataTable)dgv_tran.DataSource;
            d_1 = (decimal)dt_put.Compute("Sum(" + dt_put.Columns["planqty"].ColumnName + ")", "true");
            d_2 = (decimal)dt_put.Compute("Sum(" + dt_put.Columns["planamount"].ColumnName + ")", "true");
            d_3 = (decimal)dt_put.Compute("Sum(" + dt_put.Columns["skuamount"].ColumnName + ")", "true");
            d_4 = (decimal)dt_put.Compute("Sum(" + dt_put.Columns["shouldqty"].ColumnName + ")", "true");
            d_5 = (decimal)dt_put.Compute("Sum(" + dt_put.Columns["allocateqty"].ColumnName + ")", "true");
            d_6 = (decimal)dt_put.Compute("Sum(" + dt_put.Columns["allocateamount"].ColumnName + ")", "true");
            d_7 = (decimal)dt_put.Compute("Sum(" + dt_put.Columns["shotqty"].ColumnName + ")", "true");
            DataRow dr = dt_put.NewRow();
            dr["barcode"] = "合计";
            dr["planqty"] = d_1;
            dr["planamount"] = d_2;
            dr["skuamount"] = d_3;
            dr["shouldqty"] = d_4;
            dr["allocateqty"] = d_5;
            dr["allocateamount"] = d_6;
            dr["shotqty"] = d_7;
            ((DataTable)dgv_tran.DataSource).Rows.InsertAt(dr, ((DataTable)dgv_tran.DataSource).Rows.Count);
        }


        private void btn_Query_Click(object sender, EventArgs e)
        {
            if (!chkBox_yhday.Checked && !chkBox_bhday.Checked) {
                MessageBox.Show("'要货日期'与'备货日期'至少选一个!");
                return;
            }

            lb_rows.Text = "总行数：0";

            // 设置为忙碌状态
            Cursor.Current = Cursors.WaitCursor;

            string str_sql = "SELECT RTRIM(a.so_day) so_day,RTRIM(a.so_no) so_no,RTRIM(a.customer_code) customer_code,RTRIM(c.consignor_name) consignor_name, " +
                        "RTRIM(b.sku) sku,RTRIM(d.sku_name) sku_name,RTRIM(d.barcode) barcode," +
                        "CAST(SUM(mp.qty02) AS DECIMAL(13, 0)) as box_spec, mp.unitsPerDelivery," +
                        //"ISNULL(CAST(mp.qty02 AS INT), 0)  as box_spec," +
                        "CAST(SUM(b.plan_so_qty_m) AS DECIMAL(13, 0)) AS planqty,CAST(SUM(b.order_price * b.plan_so_qty_m) AS DECIMAL(13, 3)) AS planamount,"+
                        "CAST(SUM(d.price * b.plan_so_qty_m) AS DECIMAL(13, 3)) AS skuamount, CAST(SUM(b.plan_so_qty_m) AS DECIMAL(13, 0)) AS shouldqty," +  
                        "CONVERT(VARCHAR(10), a.prepare_time, 102) AS prepareday,"+
                        "CAST(SUM(b.allocate_qty_m) AS DECIMAL(13, 0)) AS allocateqty,CAST(SUM(b.allocate_qty_m * b.order_price) AS DECIMAL(13, 3)) AS allocateamount,"+
                        "CAST(SUM(b.plan_so_qty_m - b.allocate_qty_m) AS DECIMAL(13, 0)) AS shotqty," +
                        "RTRIM(a.standby_11) AS applyer, " +
                        "RTRIM(d.class_code1) class_code1," +
                        "RTRIM(d.class_code2) class_code2," +
                        "RTRIM(d.class_code3) class_code3," +
                        "RTRIM(sc1.class_name) as class_name1," +
                        "RTRIM(sc2.class_name) as class_name2," +
                        "RTRIM(sc3.class_name) as class_name3," +
                        "isnull(RTRIM(a.memo),'') as memo, RTRIM(f.warehouse) warehouse " +
                        "FROM  WMS.so_ship_header a " +
                        "JOIN  WMS.so_ship_detail b ON a.so_no = b.so_no AND a.inv_org = b.inv_org AND a.consignor = b.consignor " +
                        "JOIN  WMS.mst_customer c ON a.customer_code = c.consignor " +
                        "JOIN  WMS.mst_sku d ON b.sku = d.sku AND b.inv_org = d.inv_org AND b.consignor = d.consignor " +
                        "LEFT JOIN  WMS.mst_stat_class sc1 ON d.class_code1 = sc1.class_code and sc1.class_flag = 'C1' " +
	                    "LEFT JOIN  WMS.mst_stat_class sc2 ON d.class_code2 = sc2.class_code and sc2.class_flag = 'C2' " +
                        "LEFT JOIN  WMS.mst_stat_class sc3 ON d.class_code3 = sc3.class_code and sc3.class_flag = 'C3' " +
                        "left JOIN  WMS.mst_location e ON d.inv_org = e.inv_org AND d.fix_location = e.location_code " +
                        "left JOIN  WMS.mst_area f ON e.inv_org = f.inv_org AND e.area_code = f.area_code " +
                        "LEFT JOIN  WMS.mst_pack mp on mp.inv_org = d.inv_org and mp.consignor = d.consignor and mp.sku=d.sku and mp.pack_code=d.pack_code " +
                        " WHERE  a.inv_org ='" + main.g_org + "' and (a.so_type='0' or a.so_type='3')"; // so_type 0-出库 1-退货 3-调拨出库

            string str_sql_where = "";
            if (cb_consignor.Text.Trim() != "")
            {
                str_sql_where = " and a.consignor = '" + cb_consignor.Text.Trim() + "'";
            }

            if (chkBox_yhday.Checked) {

                str_sql = str_sql + " and a.so_day between '" + dtp_h_time.Text.ToString().Trim() + "' and '" + dtp_h_endtime.Text.ToString().Trim() + "'";
            }

            if (chkBox_bhday.Checked)
            {
                str_sql = str_sql + " and convert(char(10),a.prepare_time,102) between '" + dtp_b_time.Text.ToString().Trim() + "' and '" + dtp_b_endtime.Text.ToString().Trim() + "'";
            }

            //判断订单号
            if (tb_sono.Text.Trim() != "")
            {
                str_sql = str_sql + " and a.so_no = '" + tb_sono.Text.Trim() + "'";
            }
            //判断门店号
            if (tb_customer_code.Text.Trim() != "")
            {
                string[] custList = tb_customer_code.Text.Trim().Split(',');
                string custWhere = "";
                if (custList.Length > 0) {
                    foreach (string item in custList) {
                        if (custWhere == "")
                        {
                            custWhere = "'" + item + "'";
                        }
                        else {
                            custWhere += ",'" + item + "'";
                        }
                    }
                    str_sql = str_sql + " and a.customer_code in (" + custWhere + ")";
                }
                //str_sql = str_sql + " and a.customer_code = '" + tb_customer_code.Text.Trim() + "'";
            }
            //判断商品码
            if (tb_sku.Text.Trim() != "")
            {
                string[] skuList = tb_sku.Text.Trim().Split(',');
                string skuWhere = "";
                if (skuList.Length > 0)
                {
                    foreach (string item in skuList)
                    {
                        if (skuWhere == "")
                        {
                            skuWhere = "'" + item + "'";
                        }
                        else
                        {
                            skuWhere += ",'" + item + "'";
                        }
                    }
                    str_sql = str_sql + " and b.sku in (" + skuWhere + ")";
                }

                //str_sql = str_sql + " and b.sku = '" + tb_sku.Text.Trim() + "'";
            }
            //区域编码
            if (tb_area.Text.Trim() != ""){

                str_sql = str_sql + " and f.warehouse = '" + tb_area.Text.Trim() + "'";
            }
            str_sql += " group by a.so_day,a.so_no,a.customer_code,c.consignor_name,b.sku,d.sku_name,mp.qty02,mp.unitsPerDelivery,d.barcode,a.made_time,a.standby_11,d.class_code1,d.class_code2,d.class_code3,sc1.class_name,sc2.class_name,sc3.class_name,a.memo,CONVERT(VARCHAR(10), a.prepare_time, 102),f.warehouse ";
            str_sql += " order by a.so_no,a.customer_code ";
            try
            {
                if (main.dbtype == "SQL")
                {
                    ds_tran = main.dbservice.Sql_exec_selectsql(str_sql);
                }
                else
                {
                    ds_tran = main.dbservice.oracle_exec_selectsql(str_sql);
                }
                if (ds_tran.Tables[0].Rows.Count > 0)
                {
                    lb_rows.Text = "总行数：" + ds_tran.Tables[0].Rows.Count.ToString();
                    dgv_tran.DataSource = ds_tran.Tables[0];
                    f_add_order();
                }
                else
                    dgv_tran.DataSource = null;
            }
            catch (System.Exception ee)
            {
                dgv_tran.DataSource = null;
                MessageBox.Show(main.g_class.comm_getchangestring("Fail to Query", main.g_info_dataset) + "!" + ee.ToString());
            }
            Cursor.Current = currentCursor;
        }

        private void w_so063_Load(object sender, EventArgs e)
        {
            
            dscustomer = new DataSet();
            
          
            try
            {
                dscustomer = new DataSet();
                dscustomer = main.g_class.comm_get_consignor();
                cb_consignor.DataSource = dscustomer.Tables[0];
                cb_consignor.ValueMember = "consignor";
                cb_consignor.DisplayMember = "consignor";

                //语言转换
                main.g_class.comm_changeControl(this, main.g_win_dataset);
            }
            catch (System.Exception ee)
            {
                MessageBox.Show(main.g_class.comm_getchangestring("Fail to initialize Information of transaction type", main.g_info_dataset) + "!" + ee.ToString());
                return;
            }
            
            dtp_h_time.CustomFormat = "yyyy.MM.dd";
            dtp_h_time.Format = DateTimePickerFormat.Custom;
            dtp_h_time.Value = System.Convert.ToDateTime(DateTime.Now.ToString("yyyy.MM.dd").Trim());
            dtp_h_endtime.CustomFormat = "yyyy.MM.dd";
            dtp_h_endtime.Format = DateTimePickerFormat.Custom;
            dtp_h_endtime.Value = System.Convert.ToDateTime(DateTime.Now.ToString("yyyy.MM.dd").Trim());

            dtp_b_time.CustomFormat = "yyyy.MM.dd";
            dtp_b_time.Format = DateTimePickerFormat.Custom;
            dtp_b_time.Value = System.Convert.ToDateTime(DateTime.Now.ToString("yyyy.MM.dd").Trim());
            dtp_b_endtime.CustomFormat = "yyyy.MM.dd";
            dtp_b_endtime.Format = DateTimePickerFormat.Custom;
            dtp_b_endtime.Value = System.Convert.ToDateTime(DateTime.Now.ToString("yyyy.MM.dd").Trim());

          
           
           
        }

        private void dgv_tran_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void lb_batchno_Click(object sender, EventArgs e)
        {

        }

        private void dgv_tran_CellClick(object sender, DataGridViewCellEventArgs e)
        {
           // i_trans_header = e.ColumnIndex;

        }

        private void dgv_tran_Sorted(object sender, EventArgs e)
        {
            //string str_headertext;
            ////先删除合计行
            //((DataTable)dgv_tran.DataSource).Rows.Remove(((DataTable)dgv_tran.DataSource).Select("pack_code = '合计'")[0]);
            ////然后对Tables[0]重新排序
            //DataTable dt;
            //DataView dv = ((DataTable)dgv_tran.DataSource).DefaultView;
            ////得到点击的列
            //str_headertext = dgv_tran.Columns[i_trans_header].DataPropertyName.ToString().Trim();
            //if (b_trans_sort) //升序
            //{
            //    dv.Sort = str_headertext + " DESC";
            //    b_trans_sort = false;
            //}
            //else
            //{
            //    dv.Sort = str_headertext;
            //    b_trans_sort = true;
            //}
            //dt = dv.ToTable();
            //dgv_tran.DataSource = null;
            //dgv_tran.DataSource = dt;
            ////增加合计行
            //f_add_transf();
        }

        private void cb_consignor_TextChanged(object sender, EventArgs e)
        {
            string str_cust;
            str_cust = cb_consignor.Text.Trim();
            tb_cusname.Text = main.g_class.comm_findname(str_cust, dscustomer);
        }

        private void dgv_tran_DoubleClick(object sender, EventArgs e)
        {
             
        }
        private void btn_excel_Click(object sender, EventArgs e)
        {
            if (dgv_tran.Rows.Count > 0)
            {
                main.g_class.DataGridViewToExcel(dgv_tran);
            }
        }


        //复制某一列值到剪贴板
        private void CopyColumnValueToClipboard(DataGridView dgv, int rowIndex, int columnIndex)
        {
            if (dgv.Rows.Count <= rowIndex || columnIndex < 0)
            {
                // 检查索引是否超出范围
                return;
            }

            string value = dgv.Rows[rowIndex].Cells[columnIndex].Value.ToString();
            if (value != null)
            {
                Clipboard.SetText(value);


                MessageBox.Show("已复制到剪贴板");
            }
        }

        private void dgv_tran_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            int i_temp = dgv_tran.CurrentRow.Index;
            string str_name = dgv_tran.Columns[dgv_tran.CurrentCell.ColumnIndex].Name.ToString().Trim();
            //if (str_name == "so_no")
            //{

                //如果你想复制第二行第三列的值：
            CopyColumnValueToClipboard(dgv_tran, i_temp, dgv_tran.CurrentCell.ColumnIndex);
            //}
        }

        private void btn_q_customer_code_Click(object sender, EventArgs e)
        {
            w_query_batch wsingle = new w_query_batch();
            wsingle.ShowDialog();
            this.tb_customer_code.Text = w_query_batch.str_qcontent;
        }

        private void btn_q_sku_Click(object sender, EventArgs e)
        {
            w_query_batch wsingle = new w_query_batch();
            wsingle.ShowDialog();
            this.tb_sku.Text = w_query_batch.str_qcontent;
        }

        private void dgv_tran_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            //自动编号，与数据无关
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
               e.RowBounds.Location.Y,
               dgv_tran.RowHeadersWidth - 4,
               e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics,
                  (e.RowIndex + 1).ToString(),
                   dgv_tran.RowHeadersDefaultCellStyle.Font,
                   rectangle,
                   dgv_tran.RowHeadersDefaultCellStyle.ForeColor,
                   TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }

        // 删除行
        private void dgv_tran_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                ContextMenu m = new ContextMenu(); // 创建一个 ContextMenu
                MenuItem deleteRowItem = new MenuItem("删除行"); // 创建一个 MenuItem
                deleteRowItem.Click += dgv_tran_DeleteRowItem_Click; // 添加点击事件
                m.MenuItems.Add(deleteRowItem);

                int currentMouseOverRow = dgv_tran.HitTest(e.X, e.Y).RowIndex;   // 将 MenuItem 添加到 ContextMenu
                m.Show(dgv_tran, new Point(e.X, e.Y));                           // 显示 ContextMenu
            }
        }

        private void dgv_tran_DeleteRowItem_Click(object sender, EventArgs e)
        {

            w_dgv_deleterow wsingle = new w_dgv_deleterow();
            wsingle.ShowDialog();
            int i_row_start = w_dgv_deleterow.i_row_start - 1;
            int i_row_end = w_dgv_deleterow.i_row_end - 1;

            // 确保起始行和结束行在有效范围内
            if (i_row_start < 0) return;
            if (i_row_end >= dgv_tran.Rows.Count || i_row_start > i_row_end)
            {
                MessageBox.Show("超出有效范围！");
                return;
            }

            // 从 DataGridView 中删除指定范围的行 (从后向前删除行，避免索引变化问题)
            for (int i = i_row_end; i >= i_row_start; i--)
            {
                dgv_tran.Rows.RemoveAt(i);
            }

        }
    }
}